use askama_axum::Template;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;

use crate::services::frontend::config_service::ConfigService;

// SEO数据
#[derive(Deserialize, Serialize)]
pub struct FrontendFragment { 
    pub name: String,
    pub seo_title: String,
    pub seo_keywords: String,
    pub seo_description: String
}

impl FrontendFragment {
    async fn init(db:&PgPool, seo_title: &str, seo_keywords: &str, seo_description: &str) -> Self {
        if !seo_title.is_empty() && !seo_keywords.is_empty() && !seo_description.is_empty() {
            return Self {
                name: "青云凌风".to_string(),
                seo_title: seo_title.to_string(),
                seo_keywords: seo_keywords.to_string(),
                seo_description: seo_description.to_string()
            };
        }
        let config_res = ConfigService::get_config(db).await;
            match config_res {
                Ok(data) => {
                    return Self {
                        name: data.name,
                        seo_title: data.seo_title,
                        seo_keywords: data.seo_keywords,
                        seo_description: data.seo_description
                    };
                },
                Err(_) => {
                    return Self {
                        name: "青云凌风".to_string(),
                        seo_title: "青云凌风".to_string(),
                        seo_keywords: "青云凌风".to_string(),
                        seo_description: "青云凌风".to_string()
                    };
                } 
            }
    }
}

#[derive(Template)]
#[template(path = "frontend/error.html")]
struct ErrorTemplate {
    msg: String
}

pub mod home_controller;